<template>
  <view class="u-flex u-flex-wrap" v-if="couponList && couponList.length">
    <template v-for="(coupon, index) in couponList">
      <view v-if="showCoupon(coupon)" class="coupon-item" :key="index" @click="receiveCoupon(coupon)">
        <view class="coupon-left">
          <view class="price u-line-1">￥{{ coupon.coupon_price }}</view>
          <view class="text u-line-1">满{{ coupon.coupon_threshold_price }}元可用</view>
        </view>
        <view class="coupon-right">
          <view>优惠券</view>
          <view>领取</view>
        </view>
      </view>
    </template>
  </view>
</template>

<script>
import * as API_Promotions from '@/api/promotions'
import * as API_Member from '@/api/members'

export default {
  name: 'ShopCoupon',
  props: {
    shopId: [String, Number]
  },
  data() {
    return {
      couponList: [],
    }
  },
  mounted() {
    this.getShopCoupons()
  },
  methods: {
    // 读取店铺优惠券
    getShopCoupons() {
      API_Promotions.getShopCoupons(this.shopId).then(res => {
        this.couponList = res
      })
    },
    // 领取优惠券
    receiveCoupon(coupon) {
      this.judgeLogin(() => {
        uni.showLoading({ title: '请稍候...' })
        API_Member.receiveCoupons(coupon.coupon_id).then(() => {
          this.$u.toast('领取成功')
        }).finally(uni.hideLoading)
      })
    },
    // 计算是否显示优惠券
    // 如果想改为"只显示可领优惠券"，可以去掉return true，打开下面的注释
    showCoupon(coupon) {
      return true
      // if (Number(coupon.limit_num) === 0) return true
      // return Number(coupon.limit_num) !== Number(coupon.received_num)
    }
  }
}
</script>

<style lang="scss" scoped>
.coupon-item {
  width: 320rpx;
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin: 20rpx 26rpx;
  text-align: center;
  .coupon-left {
    padding: 20rpx;
    width: 200rpx;
    border-radius: 8rpx 0rpx 0rpx 8rpx;
    background: linear-gradient(to right, #2979ff 0%, #2979ff 100%);
    color: #FFFFFF;
    .price {
      font-size: 40rpx;
      font-weight: 600;
    }
    .text {
      font-size: 22rpx;
    }
  }
  .coupon-right {
    padding: 20rpx 0rpx;
    width: 120rpx;
    border-radius: 0rpx 8rpx 8rpx 0rpx;
    background-color: #FFFFFF;
    color: #2979ff;
  }
}
</style>
